from django.contrib.admin.templatetags.admin_list import pagination
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from apps.goods.models import GoodsCategory, SKU
from apps.orders.models import OrderGoods

from config import settings
from utils.categories import get_categories, get_breadcrumb
from utils.response_code import RETCODE


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        # 获取商品分类
        categories = get_categories()
        # 获取当前分类
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return render(request, '404.html')
        # 获取排序字段
        sort = request.GET.get('sort', 'default')
        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = 'create_time'

        # 获取商品列表skus
        skus = category.sku_set.filter(is_launched=True).order_by(sort_field)
        # 每页显示的商品数量
        per_page = 5
        paginator = Paginator(skus, per_page)
        try:
            page_skus = paginator.page(page_num)
        except:
            page_num = 1
            page_skus = paginator.page(page_num)
        total_page = paginator.num_pages

        # 获取面包屑导航
        breadcrumb = get_breadcrumb(category)

        # 构造上下文
        context = {
            'categories': categories,
            'page_skus': page_skus,
            'category_id': category_id,
            'total_page': total_page,
            'page_num': page_num,
            'breadcrumb': breadcrumb,
        }
        return render(request, 'list.html', context=context)


class HotGoodsView(View):
    """热销排行"""

    def get(self, request, category_id):
        # 查询热销数据（结果为SKU模型类的对象列表）
        skus = SKU.objects.filter(
            category_id=category_id, is_launched=True).order_by('-sales')[:2]
        # 将模型列表转字典构造JSON数据
        hot_skus = []
        for sku in skus:
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': settings.STATIC_URL + 'images/goods/' + sku.default_image.url + '.jpg'
            }
            hot_skus.append(sku_dict)
        print(hot_skus)
        return JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'hot_skus': hot_skus
        })


from django.views import View
from django.shortcuts import render


class GoodsDetailView(View):
    def get(self, request, sku_id):
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')
        # 查询商品频道分类
        categories = get_categories()
        # 获取面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id # 设置当前商品的规格参数
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'stock': sku.stock,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)

class GoodsCommentView(View):
    """订单商品评价信息"""

    def get(self, request, sku_id):
        # 获取被评价的订单商品信息
        order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:30]
        comment_list = []
        for order_goods in order_goods_list:
            username = order_goods.order.user.username
            comment_list.append({
                'username': username[0] + '***' + username[-1]
                if order_goods.is_anonymous else username,
                'comment': order_goods.comment,
                'score': order_goods.score,
            })
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK',
                             'comment_list': comment_list})